package com.lagou.task17;

import java.io.*;

public class BufferByteCopyTest {
    public static void copyBufferByte(String path1,String path2){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path1));
            bos = new BufferedOutputStream(new FileOutputStream(path2));
            int res = 0;
            byte[] arr =  new byte[1024];
            while ((res = bis.read(arr)) != -1){
                bos.write(arr,0,res);
            }
            System.out.println("拷贝成公");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void copyBufferReaderAndWriter(String path1,String path2){
        BufferedReader br1 = null;
        BufferedWriter bw1 = null;
        try {
            //BufferedWriter和BufferedReader
//        创建BufferedReader对象关联文件
            br1 = new BufferedReader(new FileReader(path1));
//          创建BufferedWriter对象关联文件
            bw1 = new BufferedWriter(new FileWriter(path2));
//        不断的从文件读区一行数据写入到文件
            System.out.println("正在玩命拷贝中");
            String s1  = null;
            while ((s1 = br1.readLine()) != null){
                bw1.write(s1);
                bw1.newLine();
            }
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //        关闭流对象
            if (br1 != null) {
                try {
                    br1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw1 != null) {
                try {
                    bw1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
    public static void main(String[] args) {
//        BufferedOutputStream和BufferedInputStream拷贝数据
        long time1 = System.currentTimeMillis();
        copyBufferByte("知心爱人.mp3","知心爱人1.mp3");
        long time2 = System.currentTimeMillis();
        System.out.println("使用缓冲流时间：" +(time2-time1));

//        BufferedWriter和BufferedReader
        copyBufferReaderAndWriter("a.txt","c.txt");

    }
}
